package gatesvr

import (
	"fmt"
	"lnzw/common/banner"
	"lnzw/common/proto/common_gen"
	"lnzw/engine/cluster"
	"lnzw/engine/log"
	"lnzw/engine/net/marshal"
	"lnzw/engine/net/tcp"
	"lnzw/engine/pprofile"
	"lnzw/engine/work"
	"lnzw/engine/yaml"
	"lnzw/server/logic/base"
	"lnzw/server/logic/cmd"
	_ "lnzw/server/logic/init"
	"lnzw/server/logic/node"
	"runtime/debug"

	"go.uber.org/zap"
)

type GateServer struct {
	*tcp.TcpServer
}

func (g *GateServer) Start() {
	defer func() {
		if err := recover(); err != nil {
			bs := debug.Stack()
			log.Logger.Error("GateServer Start error", zap.Any("err", err), zap.Any("stack", string(bs)))
		}
	}()
	banner := banner.NewDefaultBanner()
	fmt.Println(banner.Get("GATE SERVER"))
	pprofile.Setup()
	//安装日志
	log.Setup()
	//读取配置
	yaml.Setup()
	//工作队列
	work.Setup()
	//cmd
	cmd.Setup()
	//集群配置
	cluster.Setup()
	cluster.DEFAULT.Init(cluster.ETCD, &node.GateNode{
		DefaultNode: cluster.DefaultNode{Id: 1, Data: &node.GateNodeData{Addr: "127.0.0.1:8080"}},
	})
	cluster.DEFAULT.ObserveNodeType(int32(common_gen.ServerType_gamemgr), int32(common_gen.ServerType_game))
	g.TcpServer = tcp.NewServer()
	g.BindAddress(":8080").
		BindSocketHandle(&GateSocketHandle{}).
		Encoder(&marshal.VariableEncode{FirstSendLen: base.DEFAULT_FIRST_DECODE_ENCODE_LEN}).
		Decoder(&marshal.VariableDecode{FirstRecevedLen: base.DEFAULT_FIRST_DECODE_ENCODE_LEN})
	log.Logger.Info("GateServer Start...")
	g.TcpServer.Start()
}

func (g *GateServer) Stop() {
	g.TcpServer.Stop()
}
